#include "landdialog.h"
#include "ui_landdialog.h"
#define MAX_WEEK_DATA_COUNT (24 * 7)
QVector<QTcpSocket *> sockvector;
int op_ip = 0;
admin user;
server_to_client from_server;
dev1 dev;
QVector<env_data1> month_data;
QVector<env_data1> week_data;
bool bFlag_addSeries = false;
static int count = 0;

config maxmin;

landDialog::landDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::landDialog)
{
    ui->setupUi(this);
    ui->lineEdit_password->setEchoMode(QLineEdit::Password);

    //获取本机地址
    QString localHost = QHostInfo::localHostName();
    QHostInfo info = QHostInfo::fromName(localHost);
    info.addresses();//QHostInfo的address函数获取本机ip地址
    //如果存在多条ip地址ipv4和ipv6：
    foreach(QHostAddress address,info.addresses())
    {
        if(address.protocol()==QAbstractSocket::IPv4Protocol)
        {//只取ipv4协议的地

                QString addr = address.toString();
                if(addr.section(".", 2, 2) == "0")
                {
                    myIP = addr;
                    qDebug() << myIP;
                        //qDebug() << op_ip;
                }
                //myIP = "127.0.0.1" ;//测试用
         }
    }

    //connnect的socket压栈
    int i;
    for(i = 0; i < 255; i++)
    {
        QTcpSocket *j;
        j = new QTcpSocket(this);
        sockvector.push_back(j);
    }
}

landDialog::~landDialog()
{
    delete ui;
    int i;
    for(i = 0; i < 255; i++)
    {
        sockvector.at(i)->close();
        delete sockvector.at(i);
    }
}

void landDialog::connect_to_host()
{
    qDebug() << "finding....";
    QMessageBox::information(this, "查找", "finding....");
    for(op = 0; op < sockvector.size(); op++)
    {
        QString str = "192.168.0." + QString::number(op);
        if(myIP == str)
        {
            continue;
        }
     }
}

void landDialog::on_pushButton_land_clicked()
{
    qDebug() << "isregister:" << isregister;
    if(isregister == 1)
    {
        freshslot();
        return;
    }

    qDebug() << "finding....";
    QMessageBox::information(this, "查找", "finding....");
    for(op = 0; op < sockvector.size(); op++)
    {
        QString str = "192.168.0." + QString::number(op);
        if(myIP == str)
        {
            continue;
        }
        sockvector.at(op)->connectToHost(str, PORT);
        connect(sockvector.at(op), SIGNAL(connected()), SLOT(freshslot()));
        sockvector.at(op)->waitForConnected(4);
    }
    back();
}

void landDialog::back()
{
    if(0 == lock)
    {
        for(; op < sockvector.size(); op--)
        {
            QString str = "192.168.0." + QString::number(op);
            if(myIP == str)
            {
                continue;
            }
            sockvector.at(op)->close();
        }
        QMessageBox::warning(this,"登录","无可连接客户端！！！");
    }
}

void landDialog::freshslot()
{
    lock++;
    if(isregister != 1)
    {
        op_ip = op;
        //op = 255;
    }
    //qDebug() << lock;
    QByteArray arr2 = ui->lineEdit_username->text().toLatin1();
    memcpy(user.id, arr2.data(), ADMIN_INFO_SIZE);
    QByteArray arr1 = ui->lineEdit_password->text().toLatin1();
    memcpy(user.password, arr1.data(), ADMIN_INFO_SIZE);

    char send_buf[FLAG_SIZE];
    memset(send_buf, 0, FLAG_SIZE);
    memcpy(send_buf, "#ADMI#", 6);
    memcpy(send_buf + 6, &user, sizeof(admin));

    /*admin a;
    a = *(admin*)send_buf;
    qDebug() << a.password;*/
    //qDebug() << user.id;


    qDebug() << "op_ip:" << op_ip;
    sockvector.at(op_ip)->write(send_buf, FLAG_SIZE);
    if(isregister != 1)
    {
        connect(sockvector.at(op_ip), SIGNAL(readyRead()), SLOT(recvslot()));
    }
}

void landDialog::recvslot()
{
    char  recv_buf[FLAG_SIZE];
    memset(recv_buf, 0, FLAG_SIZE);

    sockvector.at(op_ip)->read(recv_buf, FLAG_SIZE); //接收数据
    QString str(recv_buf);
    QString judge = str.section("#", 1, 1);
    qDebug() << judge;
    if("DLOK" == judge)
    {
        //跳转
        //隐藏登录界面，显示主界面
        this->accept();
    }
    else if("DLCW" == judge)
    {
        QMessageBox::warning(this,"登录","用户名或密码错误！！！");
        ui->lineEdit_username->clear();
        ui->lineEdit_password->clear();
    }
    else if("PZXG" == judge)
    {
        maxmin = *(config*)(recv_buf + 6);
        qDebug() << QString("%1").arg(maxmin.max_env.tem, 0, 'f', 1);
    }
    else if("ZCOK" == judge)
    {
        QMessageBox::information(this, "infor", "注册成功，请登录！！");
        isregister = 1;
    }
    else if("ZCSB" == judge)
    {
        QMessageBox::information(this, "infor", "注册失败！！");
    } 
	else if("LSSJ" == judge)
    {
		server_to_client from_server_tmp = *(server_to_client*)(recv_buf + 6);
        count++;
        qDebug() << "****LSSJ****";
        if (month_data.count() <= MAX_WEEK_DATA_COUNT )
        {
            month_data.append(from_server_tmp.env_data);
            week_data.append(from_server_tmp.env_data);
        }
        else
        {
            month_data.append(from_server_tmp.env_data);
        }
    }
    else if ("CXJS" == judge)
    {
        qDebug() << "****CXJS****";
        qDebug() << QString().number(count);
        bFlag_addSeries = true;
    }
    else if("DEVI" == judge)
    {
        dev = *(dev1*)(recv_buf + 6);
    }
    else if("ZTXX" == judge)
    {
        from_server = *(server_to_client*)(recv_buf + 6);
        qDebug() << QString("%1").arg(from_server.env_data.tem);
    }

}

void landDialog::on_pushButton_exit_clicked()
{
    this->close();
}

void landDialog::on_pushButton_register_clicked()
{
    if(NULL == ui->lineEdit_username->text())
    {
        QMessageBox::warning(this, "警告", "请输入用户名和密码进行注册！！");
    }

    for(op = 0; op < sockvector.size(); op++)
    {
        QString str = "192.168.0." + QString::number(op);
        if(myIP == str)
        {
            continue;
        }
        sockvector.at(op)->connectToHost(str, PORT);
        connect(sockvector.at(op), SIGNAL(connected()), SLOT(registerslot()));
        sockvector.at(op)->waitForConnected(1);
    }
    back();
}

void landDialog::registerslot()
{
    lock++;
    op_ip = op;
    op = 0;
    qDebug() << lock;
    QByteArray arr2 = ui->lineEdit_username->text().toLatin1();
    memcpy(user.id, arr2.data(), ADMIN_INFO_SIZE);
    QByteArray arr1 = ui->lineEdit_password->text().toLatin1();
    memcpy(user.password, arr1.data(), ADMIN_INFO_SIZE);

    char send_buf[FLAG_SIZE];
    memset(send_buf, 0, FLAG_SIZE);
    memcpy(send_buf, "#ZCZH#", 6);
    memcpy(send_buf + 6, &user, sizeof(admin));

    sockvector.at(op_ip)->write(send_buf, FLAG_SIZE);
    connect(sockvector.at(op_ip), SIGNAL(readyRead()), SLOT(recvslot()));
}
